#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Python基础学习系统 - 基于CSDN博客教程
原文链接：https://blog.csdn.net/zhiguigu/article/details/120217658
"""

import os
import sys
import importlib.util
from pathlib import Path

class PythonLearningSystem:
    """Python基础学习系统主类"""
    
    def __init__(self):
        self.name = "Python基础学习系统"
        self.version = "1.0"
        self.running = True
        self.project_root = Path(__file__).parent
        
    def show_welcome(self):
        """显示欢迎界面"""
        print("=" * 50)
        print(f"欢迎使用【{self.name}】V{self.version}")
        print("基于CSDN博客：万字Python基础保姆式教学")
        print("=" * 50)
        
    def show_menu(self):
        """显示功能菜单"""
        menu = """
【功能菜单】
1. 基础语法演示
2. 数据类型学习
3. 流程控制练习
4. 列表操作实战
5. 元组操作实战
6. 字符串处理
7. 字典操作
8. 函数编程
9. 综合项目：名片管理系统
10. 运行demo1.py (基础语法)
11. 运行demo2.py (数据结构)
12. 运行demo3.py (流程控制)
13. 运行demo4.py (函数进阶)
14. 运行demo5.py (文件操作)
15. 运行demo6.py (异常处理)
16. 运行demo7.py (性能优化)
17. 运行hello.py (性能优化)
0. 退出系统
"""
        print(menu)
        
    def basic_syntax_demo(self):
        """基础语法演示"""
        print("\n【基础语法演示】")
        print("-" * 30)
        
        # 1. Hello World
        print("1. Hello World示例：")
        print('print("Hello, Python!")')
        print("结果：", end=" ")
        print("Hello, Python!")
        
        # 2. 变量和输入输出
        print("\n2. 变量和输入输出：")
        name = "Python学习者"
        age = 25
        print(f"name = '{name}'")
        print(f"age = {age}")
        print(f"print(f'你好，{name}，年龄{age}岁')")
        print(f"结果：你好，{name}，年龄{age}岁")
        
        # 3. 基本运算
        print("\n3. 基本运算：")
        a, b = 10, 3
        print(f"a = {a}, b = {b}")
        print(f"a + b = {a + b}")
        print(f"a - b = {a - b}")
        print(f"a * b = {a * b}")
        print(f"a / b = {a / b}")
        print(f"a // b = {a // b}")
        print(f"a % b = {a % b}")
        print(f"a ** b = {a ** b}")
        
    def data_types_demo(self):
        """数据类型学习"""
        print("\n【数据类型学习】")
        print("-" * 30)
        
        # 整型
        num_int = 42
        print(f"整型: {num_int}, 类型: {type(num_int).__name__}")
        
        # 浮点型
        num_float = 3.14159
        print(f"浮点型: {num_float}, 类型: {type(num_float).__name__}")
        
        # 字符串
        text = "Python编程"
        print(f"字符串: '{text}', 类型: {type(text).__name__}")
        
        # 布尔型
        flag = True
        print(f"布尔型: {flag}, 类型: {type(flag).__name__}")
        
        # 类型转换
        print("\n类型转换示例：")
        str_num = "123"
        int_num = int(str_num)
        print(f"字符串'{str_num}'转为整数: {int_num}")
        
        float_num = float(str_num)
        print(f"字符串'{str_num}'转为浮点数: {float_num}")
        
    def control_flow_demo(self):
        """流程控制练习"""
        print("\n【流程控制练习】")
        print("-" * 30)
        
        # 条件判断
        score = 85
        print(f"成绩: {score}")
        if score >= 90:
            grade = "优秀"
        elif score >= 80:
            grade = "良好"
        elif score >= 70:
            grade = "中等"
        elif score >= 60:
            grade = "及格"
        else:
            grade = "不及格"
        print(f"等级: {grade}")
        
        # 循环示例
        print("\n循环示例：")
        print("for循环输出1-5：")
        for i in range(1, 6):
            print(i, end=" ")
        print()
        
        print("while循环计算1-10的和：")
        total = 0
        count = 1
        while count <= 10:
            total += count
            count += 1
        print(f"1+2+...+10 = {total}")
        
    def list_operations_demo(self):
        """列表操作实战"""
        print("\n【列表操作实战】")
        print("-" * 30)
        
        # 创建列表
        fruits = ["苹果", "香蕉", "橙子", "葡萄"]
        print(f"原始列表: {fruits}")
        
        # 添加元素
        fruits.append("草莓")
        print(f"添加草莓后: {fruits}")
        
        # 插入元素
        fruits.insert(1, "梨子")
        print(f"在索引1插入梨子后: {fruits}")
        
        # 删除元素
        fruits.remove("香蕉")
        print(f"删除香蕉后: {fruits}")
        
        # 修改元素
        fruits[0] = "红苹果"
        print(f"修改第一个元素后: {fruits}")
        
        # 列表切片
        print(f"前3个元素: {fruits[:3]}")
        print(f"后2个元素: {fruits[-2:]}")
        
        # 列表排序
        numbers = [3, 1, 4, 1, 5, 9, 2, 6]
        print(f"排序前: {numbers}")
        numbers.sort()
        print(f"排序后: {numbers}")
        
    def tuple_operations_demo(self):
        """元组操作实战"""
        print("\n【元组操作实战】")
        print("-" * 30)
        
        # 创建元组
        coordinates = (10, 20)
        colors = ("red", "green", "blue")
        print(f"坐标: {coordinates}")
        print(f"颜色: {colors}")
        
        # 元组解包
        x, y = coordinates
        print(f"解包坐标: x={x}, y={y}")
        
        # 元组不可变，但可以转换
        color_list = list(colors)
        color_list.append("yellow")
        new_colors = tuple(color_list)
        print(f"添加黄色后的元组: {new_colors}")
        
    def string_operations_demo(self):
        """字符串处理"""
        print("\n【字符串处理】")
        print("-" * 30)
        
        text = "  Python Programming  "
        print(f"原始字符串: '{text}'")
        print(f"去除空格: '{text.strip()}'")
        print(f"转为大写: '{text.upper().strip()}'")
        print(f"转为小写: '{text.lower().strip()}'")
        print(f"替换: '{text.strip().replace('Python', 'Java')}'")
        
        # 字符串格式化
        name = "小明"
        age = 18
        print(f"\n格式化字符串:")
        print(f"我的名字是{name}，今年{age}岁")
        print("我的名字是{}，今年{}岁".format(name, age))
        print("我的名字是%(name)s，今年%(age)d岁" % {"name": name, "age": age})
        
    def dict_operations_demo(self):
        """字典操作"""
        print("\n【字典操作】")
        print("-" * 30)
        
        # 创建字典
        student = {
            "name": "张三",
            "age": 20,
            "major": "计算机科学",
            "grade": "大三"
        }
        print(f"学生信息: {student}")
        
        # 访问字典
        print(f"姓名: {student['name']}")
        print(f"年龄: {student.get('age')}")
        
        # 添加和修改
        student["gpa"] = 3.8
        student["age"] = 21
        print(f"更新后: {student}")
        
        # 遍历字典
        print("\n遍历字典:")
        for key, value in student.items():
            print(f"{key}: {value}")
            
    def function_demo(self):
        """函数编程"""
        print("\n【函数编程】")
        print("-" * 30)
        
        # 定义函数
        def greet(name):
            """打招呼函数"""
            return f"你好，{name}！"
        
        def add_numbers(a, b):
            """加法函数"""
            return a + b
            
        def calculate_area(radius):
            """计算圆面积"""
            import math
            return math.pi * radius ** 2
            
        # 使用函数
        print(greet("Python学习者"))
        print(f"3 + 5 = {add_numbers(3, 5)}")
        print(f"半径为2的圆面积: {calculate_area(2):.2f}")
        
        # lambda函数
        square = lambda x: x ** 2
        print(f"lambda函数示例: 5的平方 = {square(5)}")
        
    def business_card_system(self):
        """名片管理系统"""
        print("\n【名片管理系统】")
        print("-" * 30)
        
        cards = []
        
        def show_menu():
            print("\n" + "="*30)
            print("欢迎使用【名片管理系统】V1.0")
            print("1. 新建名片")
            print("2. 显示全部")
            print("3. 查询名片")
            print("0. 退出系统")
            print("="*30)
            
        def add_card():
            print("\n【新建名片】")
            name = input("请输入姓名: ")
            phone = input("请输入电话: ")
            qq = input("请输入QQ: ")
            email = input("请输入邮箱: ")
            
            card = {
                "name": name,
                "phone": phone,
                "qq": qq,
                "email": email
            }
            cards.append(card)
            print("名片添加成功！")
            
        def show_all():
            if not cards:
                print("暂无名片记录")
                return
                
            print("\n【显示全部名片】")
            print("-" * 50)
            print("姓名\t\t电话\t\tQQ\t\t邮箱")
            print("-" * 50)
            for card in cards:
                print(f"{card['name']}\t\t{card['phone']}\t\t{card['qq']}\t\t{card['email']}")
                
        def search_card():
            if not cards:
                print("暂无名片记录")
                return
                
            name = input("请输入要查询的姓名: ")
            found = False
            
            for card in cards:
                if card['name'] == name:
                    print("\n【查询结果】")
                    print("-" * 30)
                    print(f"姓名: {card['name']}")
                    print(f"电话: {card['phone']}")
                    print(f"QQ: {card['qq']}")
                    print(f"邮箱: {card['email']}")
                    
                    action = input("\n请选择操作: 1.修改 2.删除 0.返回: ")
                    if action == "1":
                        card['phone'] = input("请输入新电话: ")
                        card['qq'] = input("请输入新QQ: ")
                        card['email'] = input("请输入新邮箱: ")
                        print("修改成功！")
                    elif action == "2":
                        cards.remove(card)
                        print("删除成功！")
                    found = True
                    break
                    
            if not found:
                print("未找到该名片")
        
        while True:
            show_menu()
            choice = input("请选择操作: ")
            
            if choice == "1":
                add_card()
            elif choice == "2":
                show_all()
            elif choice == "3":
                search_card()
            elif choice == "0":
                print("感谢使用，再见！")
                break
            else:
                print("无效选择，请重新输入")
                
    def run_demo_file(self, filename):
        """运行指定的demo文件"""
        try:
            file_path = self.project_root / filename
            if not file_path.exists():
                print(f"错误: 文件 {filename} 不存在")
                return
                
            print(f"\n【运行 {filename}】")
            print("-" * 30)
            
            # 读取并执行文件内容
            with open(file_path, 'r', encoding='utf-8') as f:
                code = f.read()
                
            # 执行代码
            exec(code)
            print(f"\n【{filename} 执行完成】")
            
        except Exception as e:
            print(f"执行 {filename} 时出错: {e}")
                
    def run(self):
        """运行学习系统"""
        self.show_welcome()
        
        while self.running:
            self.show_menu()
            choice = input("\n请选择功能(0-16): ").strip()
            
            if choice == "1":
                self.basic_syntax_demo()
            elif choice == "2":
                self.data_types_demo()
            elif choice == "3":
                self.control_flow_demo()
            elif choice == "4":
                self.list_operations_demo()
            elif choice == "5":
                self.tuple_operations_demo()
            elif choice == "6":
                self.string_operations_demo()
            elif choice == "7":
                self.dict_operations_demo()
            elif choice == "8":
                self.function_demo()
            elif choice == "9":
                self.business_card_system()
            elif choice == "10":
                self.run_demo_file("demo1.py")
            elif choice == "11":
                self.run_demo_file("demo2.py")
            elif choice == "12":
                self.run_demo_file("demo3.py")
            elif choice == "13":
                self.run_demo_file("demo4.py")
            elif choice == "14":
                self.run_demo_file("demo5.py")
            elif choice == "15":
                self.run_demo_file("demo6.py")
            elif choice == "16":
                self.run_demo_file("demo7.py")
            elif choice == "17":
                self.run_demo_file("hello.py")
            elif choice == "0":
                print("感谢使用Python基础学习系统！")
                self.running = False
            else:
                print("无效选择，请输入0-16之间的数字")

if __name__ == "__main__":
    system = PythonLearningSystem()
    system.run()